<template>
  <div></div>
</template>
<script>
import mqtt from "mqtt";
export default {
  props: {
    topic: String, //订阅主题
    //mqtt服务器地址
    mqttUrl: {
      type: Object,
      default: () => {
        return {
          head: "ws",
          host: "broker-cn.emqx.io", //ip地址
          port: 1883, //端口号
          tailPath: "mqtt", //mqtt路径  在mqtt4.x版本的时候，请求路径是直接在brokerUrl中配置的，即此处的tailPath
        };
      },
    },
    //mqtt连接参数
    mqttOpts: {
      type: Object,
      default: () => {
        return {
          clientId: "clientId-" + Math.random().toString(16).substring(2, 8), //客户端id
          username: "username", //用户名
          password: "password", //密码
          keepalive: 60, //心跳间隔
          connectTimeout: 10 * 1000, //连接超时时间
          path: "/mqtt", ///mqtt路径  在mqtt5.x版本的时候，请求路径是直接在opts中配置的，即此处的Path
        };
      },
    },
    data() {
      return {
        client: "",
        clientCount: 0,
        receivedMessage: "", //用于储存接收到的消息
      };
    },
    watch: {
      topic(newTopic) {
        if (newTopic && this.client) {
          this.client.unsubscribe(this.topic);
          this.client.subscribe(newTopic);
        }
      },
    },
    methods: {
      InitMqtt() {
        let opts = JSON.parse(JSON.stringify(this.mqttOpts));
        this.client = mqtt.connect(
          this.mqttUrl.head +
            "://" +
            this.mqttUrl.host +
            ":" +
            this.mqttUrl.port +
            "/"+
            this.mqttUrl.tailPath,
          opts
        );
        this.client.on("connect", this.handleConnect);
        this.client.on("message", this.handleMessage);
        this.client.on("reconnect", this.handleReconnect);
        this.client.on("error", this.handleError);
      },
      handleConnect() {
        console.log("mqtt连接成功");
        this.client.subscribe(this.topic);
      },
      handleMessage(topic, message) {
        this.receivedMessage = JSON.parse(message?.toString() || {});
        this.$emit("message-received", this.receivedMessage);
      },
      handleReconnect(error) {
        console.log(`正在第${this.clientCount}次重连...`, error);
        this.clientCount++;
        if (this.clientCount >= 10) {
          console.log("重连次数过多，放弃连接");
          this.client.end();
        }
      },
      handleError(error) {
        console.log("mqtt连接出错：", error);
      },
      mqttPublish(topic, message) {
        if (this.client) {
          this.client.publish(topic, JSON.stringify(message));
        }
      },
    },
    async mounted() {
      await this.InitMqtt();
    },
    beforeDestroy() {
      this.$emit("mqtt-close"); //关闭mqtt连接需要的前置操作
      //使用延迟确保消息发送完成后再关闭连接
      setTimeout(() => {
        this.client.end(true,{},()=>{
            console.log("mqtt连接已成功关闭");
        });
      }, 1000);
    },
  },
};
</script>
<style></style>
